package com.wangxiaonan.process.service.impl;

import com.wangxiaonan.process.service.ProcessService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class ProcessServiceImpl implements ProcessService {

    private static final String TEMPLATE_SUFFIX_XML = ".xml";
    private static final String TEMPLATE_SUFFIX_FTL = ".ftl";
    private static final String TEMPLATE_SUFFIX_HTML = ".html";

    @Resource(name = "fkConfiguration")
    private Configuration configuration;


    @Override
    public Template getTemplate(String templateName) {
        return getTemplate(templateName, TEMPLATE_SUFFIX_XML);
    }

    @Override
    public Template getTemplate(String templateName, String templateSuffix) {
        if (StringUtils.isEmpty(templateName) || StringUtils.isEmpty(templateSuffix)) {
            throw new NullPointerException("文件名和后缀不能为空！");
        }
        Template template;
        try {
            String fileName = templateName + templateSuffix;
            template = configuration.getTemplate(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new NullPointerException("获取freemarker模板失败！");
        }

        return template;
    }

    @Override
    public String outputTemplate(String templateName) throws IOException, TemplateException {
        Template t = getTemplate(templateName);
        Map<String, Object> params = new HashMap<>();
        params.put("fileName", t.getSourceName() + " ~\\(≧▽≦)/~");
        try (StringWriter writer = new StringWriter()) {
            t.process(params, writer);
            return writer.toString();
        }
    }

    @Override
    public void printTemplate() {
        Template t = getTemplate("test");
        StringWriter writer = new StringWriter();
        Map<String, Object> params = new HashMap<>();
        params.put("fileName", t.getSourceName());
        try {
            t.process(params, writer);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(writer.toString());
    }
}
